package com.truyen.utils;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailMail {
	private JavaMailSender mailSender;
	private MimeMessage message;
	private String fromAddress;
	private String toAddress;
	private File file;
	private boolean isAttach = false;
	private String nameFile;
	
	public MailMail() {
	}
	
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public boolean isAttach() {
		return isAttach;
	}

	public void setAttach(boolean isAttach) {
		this.isAttach = isAttach;
	}

	public String getNameFile() {
		return nameFile;
	}

	public void setNameFile(String nameFile) {
		this.nameFile = nameFile;
	}

	public void sendMail(String messageBody, String subject) {
		try {
			message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true,
					"UTF-8");
			if(isAttach){
				FileSystemResource fileSysRes = new FileSystemResource(file);
				helper.addAttachment(nameFile, fileSysRes);
			}
			helper.setFrom(fromAddress);
			helper.setSubject(subject);
			helper.setTo(toAddress);
			helper.setText(messageBody);
		} catch (MessagingException me) {
			me.printStackTrace();
		}

		try {
			mailSender.send(message);
		} catch (MailAuthenticationException ex) {
			ex.printStackTrace();
		} catch (MailException me) {
			me.printStackTrace();
		}
	}

	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}
	public MimeMessage getMessage() {
		return message;
	}

	public void setMessage(MimeMessage message) {
		this.message = message;
	}
}
